<template>
  <a-card :bordered="false">
    <a-spin :spinning="spinning != 0">

      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('m.system.org.entity.orgName')">
                <a-input placeholder="" v-model="queryParam.orgName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <div class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">{{ $t('m.common.button.query') }}</a-button>
                <a-button type="primary" @click="searchReset" icon="reload">{{ $t('m.common.button.reset') }}</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button @click="handleAddRoot" v-has="'system:SysOrg:add'" type="primary" icon="plus">{{ $t('m.common.button.add') }}</a-button>
        <!--<a-button @click="handleUpdatePath" icon="reload">整理数据(升级后临时使用)</a-button>-->
        <a-button v-has="'system:SysOrg:export'" type="default" icon="download" @click="handleExportXls($t('m.system.org.other.orgType_org'))">{{ $t('m.common.button.export') }}</a-button>
        <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
                  @change="handleImportExcel">
          <a-button v-has="'system:SysOrg:import'" type="default" icon="import">{{ $t('m.common.button.import') }}</a-button>
        </a-upload>
        <a-dropdown v-has="'system:SysOrg:add'" v-if="showDingtalk">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="syncDeptToDingtalk"><a-icon type="plus" />{{$t('m.system.user.other.syncDingTalkToRemote')}}</a-menu-item>
            <a-menu-item key="2" @click="syncDeptToLocal"><a-icon type="plus" />{{$t('m.system.user.other.syncDingTalkFromRemote')}}</a-menu-item>
          </a-menu>
          <a-button icon="plus">{{$t('m.system.user.other.syncDingTalk')}}<a-icon type="down" /></a-button>
        </a-dropdown>
      </div>

      <a-table
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :pagination="false"
        :dataSource="dataSource"
        @expand="expandSubTree"
        :expandedRowKeys="expandedRowKeys"
        @expandedRowsChange="handleExpandedRowsChange">

        <template slot="action" slot-scope="text, record">
          <a href="javascript:void(0);" v-has="'system:SysOrg:add'" @click="handleAddSub(record)">{{ $t('m.system.org.other.add_sub') }}</a>
          <a-divider type="vertical"/>
          <a href="javascript:void(0);" v-has="'system:SysOrg:edit'" @click="handleEdit(record)">{{ $t('m.common.button.update') }}</a>
          <a-divider type="vertical"/>
          <a-popconfirm :title="$t('m.common.tip.delete_confirm')" @confirm="() => handleDelete(record)" v-test>
            <a href="javascript:void(0);" v-has="'system:SysOrg:delete'">{{ $t('m.common.button.delete') }}</a>
          </a-popconfirm>
        </template>

      </a-table>

    </a-spin>

    <sys-org-dialog ref="sysOrgModal" @refreshParent="loadData"></sys-org-dialog>
  </a-card>
</template>
<script>

  import { getAction, deleteAction, putAction, postAction } from '@/api/manage'
  import SysOrgDialog from './modules/SysOrgDialog'
  import { SystemConstant } from './SystemConstant'
  import { YcListMixin } from '@/mixins/YcListMixin'
  import YchConstant from "@/api/YchConstant";
  import config from '@/settings'

  export default {
    name: 'DepartList',
    mixins: [YcListMixin],
    components: {
      SysOrgDialog
    },
    data() {
      return {
        showDingtalk: config.showDingtalk,
        queryParam: {},
        columns: [{
          title: this.$t('m.system.org.entity.orgName'),
          align: 'left',
          dataIndex: 'orgName',
          width: 150
        }, {
          title: this.$t('m.system.org.entity.orgCode'),
          align: 'center',
          dataIndex: 'orgCode',
          width: 120
        }, {
          title: this.$t('m.system.org.entity.orgType'),
          align: 'center',
          dataIndex: 'orgType',
          width: 120,
          customRender: function(t, r, index) {
            return SystemConstant.orgType.find(vo => vo.value == t).label
          }
        }, {
          title: this.$t('m.system.org.entity.orgOrder'),
          align: 'center',
          dataIndex: 'orgOrder',
          width: 40
        }, {
          title: this.$t('m.common.label.operate'),
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 120
        }],
        dataSource: [],
        spinning: 0,
        expandedRowKeys: [],
        url: {
          queryRootTreeList: YchConstant.PREFIX_SYSTEM + '/sysOrg/queryRootTreeList',
          querySubTreeList: YchConstant.PREFIX_SYSTEM + '/sysOrg/querySubTreeList',
          queryTreeListBatch: YchConstant.PREFIX_SYSTEM + '/sysOrg/queryTreeListBatch',
          delete: YchConstant.PREFIX_SYSTEM + '/sysOrg/delete',
          getMaxOrder: YchConstant.PREFIX_SYSTEM + '/sysOrg/getMaxOrder',
          searchTreeList: YchConstant.PREFIX_SYSTEM + '/sysOrg/searchTreeList',
          updatePath: YchConstant.PREFIX_SYSTEM + '/sysOrg/updatePath',
          exportXlsUrl: YchConstant.PREFIX_SYSTEM + '/sysOrg/exportExcel',
          importExcelUrl: YchConstant.PREFIX_SYSTEM + '/sysOrg/importExcel',
          syncDeptToDingtalk: YchConstant.PREFIX_SYSTEM + '/sync/dingtalk/syncDeptToDingtalk',
          syncDeptToLocal: YchConstant.PREFIX_SYSTEM + '/sync/dingtalk/syncDeptToLocal',
        }
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${bootConfig[process.env.NODE_ENV].VUE_APP_API}${this.url.importExcelUrl}`
      }
    },
    methods: {
      searchQuery() {
        if (this.queryParam.orgName) {
          this.spinning++
          getAction(this.url.searchTreeList, this.queryParam).then((res) => {
            if (res.success) {
              this.dataSource = res.result || []
              this.expandedRowKeys = []
              this.setExpandkey(this.dataSource)
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.spinning--
          })
        } else {
          this.loadData()
        }
      },
      setExpandkey(dataSource) {
        dataSource.forEach(item => {
          if (item.children) {
            this.expandedRowKeys.push(item.id)
            this.setExpandkey(item.children)
          }
        })
      },
      searchReset() {
        this.queryParam = {}
        this.loadData()
      },
      handleAddRoot() {
        const pk = [{
          colCode: 'orgType',
          queryValue: '1'
        }]
        this.spinning++
        getAction(this.url.getMaxOrder).then((res) => {
          if (res.success) {
            pk.push({
              colCode: 'orgOrder',
              queryValue: res.result
            })
            this.$refs.sysOrgModal.add(pk)
          } else {
            this.messageUtil.warning(res.message)
          }
        }).finally(() => {
          this.spinning--
        })
      },
      handleEdit(record) {
        this.$refs.sysOrgModal.edit(record.id)
      },
      handleAddSub(record) {
        const pk = [{
          colCode: 'parentId',
          queryValue: record.id
        }, {
          colCode: 'orgType',
          queryValue: record.orgType
        }]
        this.spinning++
        getAction(this.url.getMaxOrder, { parentId: record.id }).then((res) => {
          if (res.success) {
            pk.push({
              colCode: 'orgOrder',
              queryValue: res.result
            })
            this.$refs.sysOrgModal.add(pk)
          } else {
            this.messageUtil.warning(res.message)
          }
        }).finally(() => {
          this.spinning--
        })
      },
      handleDelete(record) {
        this.spinning++
        deleteAction(this.url.delete, { id: record.id }).then((res) => {
          if (res.success) {
            this.messageUtil.success(res.message)
            this.loadData()
          } else {
            this.messageUtil.warning(res.message)
          }
        }).finally(() => {
          this.spinning--
        })
      },
      loadData() {
        this.spinning++
        getAction(this.url.queryRootTreeList).then((res) => {
          if (res.success) {
            this.dataSource = res.result || []
            if (this.dataSource.length > 0 && this.expandedRowKeys.indexOf(this.dataSource[0].id) == -1 && this.dataSource[0].children) {
              this.expandedRowKeys = [...this.expandedRowKeys, this.dataSource[0].id]
            }
            this.loadDataByExpandedRows(this.dataSource)
          } else {
            this.messageUtil.warning(res.message)
          }
        }).finally(() => {
          this.spinning--
        })
      },
      expandSubTree(expanded, record) {
        if (expanded && record.children.length === 0) {
          this.spinning++
          getAction(this.url.querySubTreeList, { parentId: record.id }).then((res) => {
            if (res.success) {
              record.children = res.result || []
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.spinning--
          })
        }
      },
      loadDataByExpandedRows(dataList) {
        if (this.expandedRowKeys.length > 0) {
          this.spinning++
          getAction(this.url.queryTreeListBatch, { parentIds: this.expandedRowKeys.join(',') }).then((res) => {
            if (res.success) {
              const childrenMap = res.result
              const fn = (list) => {
                if (list == null) {
                  return
                }
                list.forEach(data => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = childrenMap[data.id]
                    fn(data.children)
                  }
                })
              }
              fn(dataList)
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.spinning--
          })
        }
      },
      handleExpandedRowsChange(expandedRows) {
        this.expandedRowKeys = expandedRows
      },
      handleUpdatePath() {
        const that = this
        this.$confirm({
          content: this.$t('m.system.org.other.handle_update_path'),
          onOk: function() {
            that.spinning++
            putAction(that.url.updatePath).then((res) => {
              if (res.success) {
                that.messageUtil.success(res.message)
                that.loadData()
              } else {
                that.messageUtil.warning(res.message)
              }
            }).finally(() => {
              that.spinning--
            })
          }
        })
      },
      syncDeptToDingtalk(){
        let url = this.url.syncDeptToDingtalk
        this.synDingTalk(url,[])
      },
      syncDeptToLocal() {
        let url = this.url.syncDeptToLocal
        this.synDingTalk(url,[])
      },

      synDingTalk(url,selectedRowKeys){
        let content = this.$t('m.system.user.verify.synDingtalkUserConfirm')
        if (Array.isArray(selectedRowKeys) && selectedRowKeys.length > 0) {
          content = this.$t('m.system.user.verify.synSelectDingtalkUserConfirm',[selectedRowKeys.length])
        } else {
          selectedRowKeys = []
        }
        return new Promise((resolve, reject) => {
          let model = this.$confirm({
            title: this.$t('m.system.user.other.synDingTalkTitle'),
            content,
            onOk: () => {
              model.update({
                keyboard: false,
                okText: this.$t('m.system.user.other.synDingTalkTips'),
                cancelButtonProps: {props: {disabled: true}}
              })
              return postAction(url, {
                ids: selectedRowKeys.join(',')
              }).then(res => {
                let options = null
                if (res.result) {
                  options = {
                    width: 600,
                    title: res.message,
                    content: (h) => {
                      let nodes
                      let successInfo = [
                        this.$t('m.system.user.other.synDingTalkSucess'),
                        this.renderTextarea(h, res.result.successInfo.map((v, i) => `${i + 1}. ${v}`).join('\n')),
                      ]
                      if (res.success) {
                        nodes = [
                          ...successInfo,
                          h('br'),
                          this.$t('m.system.user.other.synDingTalkNoError'),
                        ]
                      } else {
                        nodes = [
                          this.$t('m.system.user.other.synDingTalkError'),
                          this.renderTextarea(h, res.result.failInfo.map((v, i) => `${i + 1}. ${v}`).join('\n')),
                          h('br'),
                          ...successInfo,
                        ]
                      }
                      return nodes
                    }
                  }
                }
                if (res.success) {
                  if (options != null) {
                    this.$success(options)
                  } else {
                    this.$message.success(res.message)
                  }
                  //this.$emit('sync-ok')
                } else {
                  if (options != null) {
                    this.$warning(options)
                  } else {
                    this.$message.warning(res.message)
                  }
                  //this.$emit('sync-error')
                }
              }).catch(() => model.destroy()).finally(() => {
                resolve()
                this.loadData()
              })
            },
            onCancel() {
              resolve()
            },
          })
        })
      },
      renderTextarea(h, value) {
        return h('a-textarea', {
          props: {
            value: value,
            readOnly: true,
            autosize: {minRows: 5, maxRows: 10},
          },
          style: {
            // 关闭textarea的自动换行，使其可以左右滚动
            whiteSpace: 'pre',
            overflow: 'auto',
          }
        })
      },
    }
  }
</script>
<style lang="less" scoped>

</style>

